//
//  SearchViewController.m
//  Emoticon
//
//  Created by ytkjs2 on 2020/4/7.
//  Copyright © 2020 ytk. All rights reserved.
//

#import "SearchViewController.h"
#import "ListViewCell.h"
#import "BagViewCell.h"
#import "SearchSwitchView.h"
#import "TagView.h"
#import "BagListViewController.h"
#import "SearchDownloadController.h"

@interface SearchViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate>
{
    UITextField * searchText;
}
@property (nonatomic, strong)NSMutableArray * collectDataSource;

@property (nonatomic, strong)NSMutableArray * tableViewDataSource;

@property (nonatomic, strong)UIScrollView * scroll;

@property (nonatomic, strong)SearchSwitchView * switchView;

@property (nonatomic, strong)TagView * tagView;

@property (nonatomic, strong)MBProgressHUD * hud;

@end

@implementation SearchViewController

- (NSMutableArray *)collectDataSource
{
    if (!_collectDataSource) {
        _collectDataSource = [NSMutableArray array];
    }
    return _collectDataSource;
}

- (NSMutableArray *)tableViewDataSource
{
    if (!_tableViewDataSource) {
        _tableViewDataSource = [NSMutableArray array];
    }
    return _tableViewDataSource;
}

- (UIScrollView *)scroll
{
    if (!_scroll) {
        _scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 45, rScreenWidth, rScreenHeight - 45)];
        _scroll.delegate = self;
        _scroll.contentSize = CGSizeMake(rScreenWidth * 2, 0);
        _scroll.showsVerticalScrollIndicator = NO;
        _scroll.pagingEnabled = YES;
        
        [self.bagCollectionView setFrame:CGRectMake(0, 0, rScreenWidth, rScreenHeight - 45)];
        [self.bagTableView setFrame:CGRectMake(rScreenWidth, 0, rScreenWidth, rScreenHeight - 45)];
        self.bagTableView.rowHeight = 90;
        
        [_scroll addSubview:_bagCollectionView];
        [_scroll addSubview:_bagTableView];
        
        _scroll.hidden = YES;
    }
    return _scroll;
}

- (TagView *)tagView
{
    if (!_tagView) {
        _tagView = [[TagView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth, 100)];
        _tagView.controller = self;
        [_tagView setTagView:SEARCH_TAG];
    }
    return _tagView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view addSubview:self.scroll];
    
    UIView * textBgView = [[UIView alloc]initWithFrame:CGRectMake(38, 8.5, rScreenWidth - 57, 30)];
    textBgView.backgroundColor = [UIColor whiteColor];
    [textBgView.layer setMasksToBounds:YES];
    [textBgView.layer setCornerRadius:16.5];
    
    searchText = [[UITextField alloc]initWithFrame:CGRectMake(14.5, 0, rScreenWidth - 86, 30)];
    searchText.placeholder = @"搜索你所感兴趣的内容吧!";
    searchText.delegate = self;
    searchText.clearButtonMode = UITextFieldViewModeWhileEditing;
    searchText.returnKeyType = UIReturnKeySearch;
    searchText.inputAccessoryView = [self addToolbar];
    [textBgView addSubview:searchText];
    
    self.navigationItem.titleView = textBgView;
    
    [self.bagCollectionView registerNib:[UINib nibWithNibName:@"ListViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ListViewCell"];
    
    _switchView = [[SearchSwitchView alloc]initWithFrame:CGRectMake(0, 0, rScreenWidth, 45) withTitleArray:@[@"表情",@"表情包"]];
    _switchView.controller = self;
    _switchView.backgroundColor = APP_THEME_COLOR;
    _switchView.hidden = YES;
    [self.view addSubview:_switchView];
    
    [self.view addSubview:self.tagView];
    
    _tagView.hidden = NO;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length < 1) {
        return NO;
    }
    
    [self reloadDataWithText:textField.text];
    
    [textField resignFirstResponder];
    return YES;
}

- (UIToolbar*)addToolbar{
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"收起" style:UIBarButtonItemStylePlain target:self action:@selector(textfieldFinish)];
    
    toolbar.items=@[space,bar];
    
    return toolbar;

}

-(void)textfieldFinish
{
    [searchText resignFirstResponder];
}

-(void)reloadDataWithText:(NSString *)text
{
    __block int skip = 0;
    __block int bagSkip = 0;
    __weak typeof(self)weakSelf = self;
    
    [searchText endEditing:YES];
    
    _collectDataSource = [NSMutableArray array];
    _tableViewDataSource = [NSMutableArray array];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
        weakSelf.hud = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
//        weakSelf.hud.bezelView.backgroundColor = RGB(1, 1, 1, 0.2);
        weakSelf.hud.animationType = MBProgressHUDAnimationFade;
        weakSelf.hud.removeFromSuperViewOnHide = YES;
        [weakSelf.hud show:YES];
    });
    
    _bagCollectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [PictureData getRequestWithServiceUrl:SEARCH_EMOTICON_URL parameters:@{@"keyword":text,@"skip":@(skip),@"limit":@"32"} success:^(id  _Nonnull responseObject) {
            
            
            NSArray * arr = [NSArray arrayWithArray:[[responseObject objectForKey:@"res"]objectForKey:@"data"]];
            
            for (NSDictionary * dic in arr) {
                SearchModel * model = [SearchModel mj_objectWithKeyValues:dic];
                [weakSelf.collectDataSource addObject:model];
            }
            
            [weakSelf.bagCollectionView reloadData];
            [weakSelf.bagCollectionView.mj_footer endRefreshing];
            skip ++;
            
            
            weakSelf.bagTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
                [PictureData getRequestWithServiceUrl:SEARCH_BAG_URL parameters:@{@"keyword":text,@"skip":@(bagSkip),@"limit":@"32"} success:^(id  _Nonnull responseObject1) {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud hide:YES];
                    });

                    NSArray * arr1 = [NSArray arrayWithArray:[[responseObject1 objectForKey:@"res"]objectForKey:@"data"]];
                               
                    for (NSDictionary * dic in arr1) {
                        SearchBagModel * model1 = [SearchBagModel mj_objectWithKeyValues:dic];
                        [weakSelf.tableViewDataSource addObject:model1];
                    }
                    
                    weakSelf.tagView.hidden = YES;
                    weakSelf.scroll.hidden = NO;
                    weakSelf.switchView.hidden = NO;
                    [weakSelf.bagTableView reloadData];
                    [weakSelf.bagTableView.mj_footer endRefreshing];
                    bagSkip++;
                } failure:^(NSError * _Nonnull error1) {
                    [weakSelf.bagTableView.mj_footer endRefreshing];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud hide:YES];
                    });
                }];
            }];
            
            [weakSelf.bagTableView.mj_footer beginRefreshing];
            
        } failure:^(NSError * _Nonnull error) {
            [weakSelf.bagCollectionView.mj_footer endRefreshing];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud hide:YES];
            });
        }];
    }];
    
    [_bagCollectionView.mj_footer beginRefreshing];
}

-(void)btnClickAction:(id)sender
{
    NSInteger tag = ((UIButton *)sender).tag;
    searchText.text = SEARCH_TAG[tag];
    [self reloadDataWithText:SEARCH_TAG[tag]];
}


#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _collectDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ListViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ListViewCell" forIndexPath:indexPath];
    
    SearchModel * model = [[SearchModel alloc]init];
    
    model = _collectDataSource[indexPath.item];
    
    NSString * imgUrl = [model.small_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [cell.IMG sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"icon_placeholderImage"]];
    
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 6.5;//上下行
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 6.5;//行距
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(6.5, 12, 6.4, 12 );//分别为上、左、下、右
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = (rScreenWidth - 61)/4;
    
    return CGSizeMake(width,width);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchDownloadController * downloadVC = [[SearchDownloadController alloc]initWithNibName:@"SearchDownloadController" bundle:nil];
    downloadVC.dataSource = [_collectDataSource mutableCopy];
    downloadVC.picIndex = indexPath.item;
    [self.navigationController pushViewController:downloadVC animated:YES];
}

#pragma mark <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableViewDataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BagViewCell * cell = [[NSBundle mainBundle]loadNibNamed:@"BagViewCell" owner:nil options:nil][0];
    
    SearchBagModel * model = _tableViewDataSource[indexPath.row];
       
    NSString * imgUrl = [model.cover stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [cell.img sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"icon_placeholderImage"]];
    
    cell.name.text = model.name;
    
    cell.desc.text = model.desc;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BagListViewController * listVC = [[BagListViewController alloc]initWithNibName:@"BagListViewController" bundle:[NSBundle mainBundle]];
    
    SearchBagModel * model = _tableViewDataSource[indexPath.row];
    listVC._id = model._id;
    listVC.title = model.name;
    [self.navigationController pushViewController:listVC animated:YES];
}

-(void)typeSelectChange:(UIButton *)btn
{
    [UIView animateWithDuration:0.2f animations:^{
        [self.scroll setContentOffset:CGPointMake(rScreenWidth * btn.tag, 0)];
    }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [searchText endEditing:YES];
    if (scrollView == _scroll) {
        NSInteger index = (scrollView.contentOffset.x + rScreenWidth/2 )/rScreenWidth;
        [_scroll setContentSize:CGSizeMake(rScreenWidth * 2, 0)];

        [_switchView scrollButtons:index];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
